/**
 * Created by zyy on 15/6/26.
 * zhangyuyu@superjia.com
 */
var message = require('./message')
var utils = {
    success: function (res, value) {
        res.body = {
            code: 200,
            data: value
        }
        return false;
    },

    failed: function (res, code) {
        
        res.body = {
            code: code,
            message: message[code] || ''
        }
        return false;
    },
    isEmail: function (v) {
        return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(v);
    },

    isMobile: function (v) {
        return /^1[3|4|5|7|8]\d{9}$/.test(v);
    },

    isMobile: function (req) {
        var phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
            + "|windows (phone|ce)|blackberry"
            + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
            + "|laystation portable)|nokia|fennec|htc[-_]"
            + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b"

        var tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
            + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b"

        var agent = req.header['user-agent'].toLowerCase()
        if (!agent)
            return false

        if (!!new RegExp(phoneReg, 'igm').exec(agent) || !!new RegExp(tableReg, 'igm').exec(agent)) {
            return true
        }
        return false
    },

    isWeixin: function (req) {
        var agent = req.header('USER-AGENT').toLowerCase()
        if (!agent)
            return false
        if (agent.match(/MicroMessenger/i) == 'micromessenger') {
            return true
        } else {
            return false
        }
    },

    extend: function (obj, obj1) {
        for (var key in obj1) {
            obj[key] = obj1[key]
        }
        return obj
    },

    wrapUser: function(user) {
        user.isSuperAdmin = user.role == 'superadmin'
        user.isAdmin = user.role == 'admin'
        user.isMember = user.role == 'member'
        delete user.password;
        return user
    },

    //delta相差天数
    fromNow: function(delta) {
        var now = new Date()

        delta = delta || delta * 86400000

        return new Date(now.getFullYear(), now.getMonth(), now.getDay()) - delta;
    }
}
module.exports = utils